import { useMemo } from 'react';

import { getIsAuth } from '@/entities/auth/model/selectors';
import { CompanyInfoCard } from '@/entities/company';
import { productApi, Program } from '@/entities/course';
import { Staff } from '@/entities/course/product.interface';
import { ratingApi } from '@/entities/rating';
import { AddToFavourite } from '@/features/AddToFavourite';
import { OpenShareModalButton } from '@/features/Share';
import { PageBlock } from '@/shared/interfaces';
import { CourseDto } from '@/shared/interfaces/generated';
import { useAppSelector } from '@/shared/store';
import { Block, SpeakerCard, Tabs } from '@/shared/ui';
import { AccordionList, List } from '@/widgets/List';
import { useRouter } from 'next/router';

import cs from './Course.module.scss';
import { AboutCourse } from './ui/AboutCourse';
import { ReviewList } from './ui/ReviewList';

export const useCourseBlocks = (): {
  blocks: PageBlock[];
  actions: Record<string, JSX.Element>;
  course: CourseDto;
  isFetching?: boolean;
  isSuccess?: boolean;
} => {
  const router = useRouter();
  const id = router.query.id as string;
  const userId = useAppSelector((state) => state.auth.userId);
  const isAuth = useAppSelector(getIsAuth);
  const [addToFavourites, { isLoading: isAdding }] = productApi.useAddProductToFavouritesMutation();
  const [deleteFromFavourites, { isLoading: isDeleting }] = productApi.useDeleteProductFromFavouritesMutation();
  const {
    data: course,
    isLoading: isFetching,
    isSuccess,
  } = productApi.useGetSingleProductQuery(id || '', { skip: !id });
  const { data: contents, isLoading: isLoadingContents } = productApi.useGetSingleProductContentsQuery(id || '', {
    skip: isFetching,
  });
  const { data: questionsRes, isLoading: isLoadingQuestions } = productApi.useGetSingleProductQuestionsQuery(
    course?.product?.id || '',
    { skip: isFetching || isLoadingContents },
  );
  const { data: ratings, isLoading: isLoadingRatings } = ratingApi.useGetProductRatingsQuery(
    String(course?.product?.id) || '',
    {
      skip: isFetching || !id,
    },
  );
  const [createReview] = ratingApi.useAddProductRatingMutation();

  const actions = {
    share: (
      <OpenShareModalButton
        data={{
          title: course?.product?.title,
          text: course?.product?.description,
        }}
        variant="icon"
      />
    ),
    like: (
      <AddToFavourite
        errorMessage={{ onAdd: 'Ошибка при добавлении в избранное: ', onDelete: 'Ошибка при удалении из избранного: ' }}
        handleAdd={() => addToFavourites({ userId: userId || undefined, productId: course?.product?.id }).unwrap()}
        handleDelete={() =>
          deleteFromFavourites({ userId: userId || undefined, productId: course?.product?.id }).unwrap()
        }
        isFavourite={!!course?.isFavorite}
        isHidden={!isAuth}
        isLoading={isAdding || isDeleting}
        successMessage={{ onAdd: 'Добавлено в избранное', onDelete: 'Удалено из избранного' }}
      />
    ),
  };
  const tabs = useMemo(() => {
    if (!id || isFetching) return null;
    const programs = [...(contents?.contents || [])]
      .sort((a, b) => a.order - b.order)
      ?.map(({ id, title, description, place }) => (
        <Program description={description} key={id} number={place} title={title} />
      ));

    const questions = [...(questionsRes?.questions || [])]
      .sort((a, b) => a.order - b.order)
      ?.map(({ id, question, answer }) => ({
        id,
        title: question.trim().split('').reverse()[0] === '?' ? question : `${question}?`,
        body: answer,
      }));
    return {
      tabs: [
        {
          id: 1,
          title: 'Содержание',
          data: programs?.length ? <List list={programs} /> : null,
        },
        {
          id: 2,
          title: 'Частые вопросы',
          data: questions?.length ? <AccordionList list={questions || []} /> : null,
        },
      ],
    };
  }, [id, isFetching, course, isLoadingContents, isLoadingQuestions]);

  const blocks = useMemo(() => {
    if (!course) {
      return [];
    }
    return [
      {
        id: 'about',
        title: 'О материале',
        body: <AboutCourse course={course} />,
      },
      {
        id: 'info',
        title: 'Информация',
        body:
          tabs && tabs.tabs && tabs.tabs.filter((item) => item.data !== null).length > 0 ? (
            <Block body={<Tabs key={id} tabs={tabs.tabs} />} key={id} title="Информация" />
          ) : undefined,
      },
      {
        id: 'speakers',
        title: <>Команда </>,
        body: (
          <Block
            body={
              <List
                list={(course?.product.staff as unknown as Staff[]).map(({ id, name, avatar, positionAtWork }) => (
                  <SpeakerCard description={positionAtWork} image={avatar} key={id} name={name} />
                ))}
              />
            }
            title="Команда"
          />
        ),
      },
      {
        id: 'reviews',
        title: (
          <>
            Отзывы
            <span className={cs.sub_title} key={ratings?.ratings?.length}>
              {ratings?.ratings?.length}
            </span>
            {/* || course?.company.numberOfComments */}
          </>
        ),
        body: (
          <ReviewList
            canCreate={!!isAuth && !!course?.isBought}
            id={String(course?.product.id)}
            onCreate={createReview}
            ratingId={course?.userRatingId as unknown as number}
            ratings={ratings?.ratings || []}
          />
        ),
      },
      {
        id: 'company',
        title: 'Компания',
        body: <Block body={<CompanyInfoCard {...course?.product.company} />} title="Компания" />,
      },
    ];
  }, [isFetching, course, isLoadingContents, isLoadingQuestions, isLoadingRatings]);
  return { course: course as CourseDto, isFetching, isSuccess, actions, blocks };
};
